import Vue from 'vue'
import VueRouter  from 'vue-router'
import axios from 'axios'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'

//挂载全局
Vue.prototype.$axios = axios //ajax请求方法

Vue.use(VueRouter)

const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  { path: '/404',component: () => import('@/views/common/404.vue'), name: '404', meta: { title: '404未找到'}},
  { path: '/login',component: () => import('@/views/common/login.vue'), name: 'login', meta: { title: '登录'}}
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: () => import('@/views/main.vue'),
  name: 'main',
  redirect: {name: 'home'}, //重定向和别名
  meta: { title: '主入口整体布局'},
  children: [
    { path: '/home',component: () => import('@/views/common/home.vue'), name: 'home', meta: {title: '首页'}},
  ],
  beforeEnter (to, from, next) {
    let token = Vue.cookie.get('token')
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
    }
    next()
  }
}

const router = new VueRouter({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),//对于所有路由导航，简单地让页面滚动到顶部。
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes) //利用conca方法拼接为一个数组
})

router.beforeEach((to, form, next)=>{
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  if(router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global'){
    next()
  }else{
    http({
      url: http.adornUrl('/sys/menu/nav'),
      method: 'get',
      params: http.adornParams()
    }).then(({data})=> {
      if(data && data.code == 0){
        fnAddDynamicMenuRoutes(data.menuList)
        router.options.isAddDynamicMenuRoutes = true
        //将菜单列表保存本地存储
        sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
        sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
        next({ ...to, replace: true })
      }else{
        sessionStorage.setItem('menuList', '[]')
        sessionStorage.setItem('permissions','[]')
				next()
      }
    }).catch((e) => {
      console.log(`%c${e} 请求菜单列表失败，跳转至登录页！！`, 'color:blue');
      router.push({name: 'login'})
    })
  }
})


/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType (route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if(menuList[i].children && menuList[i].children.length >= 1){
      temp = temp.concat(menuList[i].children)
    }else if (menuList[i].url && /\S/.test(menuList[i].url)) { //  /\S/.test()  匹配任何非空白字符
      menuList[i].url = menuList[i].url.replace(/^\//, '')  //将以"/"开头的url替换为""
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: { name: '404' } }
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->')
    console.log(mainRoutes.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->')
  }
}

export default router
